package cl.orangepeople.whyem.portal.negotiations.beans;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.inject.Named;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;

import cl.orangepeople.whyem.portal.backend.api.DebtsService;
import cl.orangepeople.whyem.portal.backend.dto.debts.DebtDataBean;
import cl.orangepeople.whyem.portal.negotiations.utils.whyemUtils;

import com.liferay.portal.kernel.concurrent.ConcurrentHashSet;

@Named("debtsListBean")
@Scope("view")
public class DebtsListBean implements Serializable {

    private static Logger logger = LoggerFactory.getLogger(DebtsListBean.class);
    private List<DebtDataBean> debtsList;
    private Set<DebtDataBean> debtsSelected;
    private long totalToPay;
    @Resource(name = "debtsService")
    private DebtsService debtsService;

    @PostConstruct
    public void initLoadDebtBean() {
        logger.info("Init con @PostConstruct");
        this.debtsList = loadDebts();
        this.debtsSelected = new ConcurrentHashSet<DebtDataBean>();
        this.totalToPay = 0L;
    }

    public List<DebtDataBean> loadDebts() {
        return debtsService.getDebtsByClientID(whyemUtils.getUserClientID());
    }

    public void refreshSelectedDebtsToPay(DebtDataBean selected) {
        boolean isRefreshed = debtsSelected.add(selected) ? true : debtsSelected.remove(selected);
        if (isRefreshed) {
            totalToPay = calculateTotalAmountToPay(debtsSelected);
        }
    }

    private long calculateTotalAmountToPay(Collection<DebtDataBean> selectedToPay) {
        long total = 0L;
        for (DebtDataBean data : selectedToPay) {
            total += Long.valueOf(data.getPaymentDetail().getAmount());
        }
        return total;
    }

    public List<DebtDataBean> getDebtsList() {
        return debtsList;
    }

    public void setDebtsList(List<DebtDataBean> debtsList) {
        this.debtsList = debtsList;
    }

    public Set<DebtDataBean> getDebtsSelected() {
        return debtsSelected;
    }

    public void setDebtsSelected(Set<DebtDataBean> debtsSelected) {
        this.debtsSelected = debtsSelected;
    }

    public long getTotalToPay() {
        return totalToPay;
    }

    public void setTotalToPay(long totalToPay) {
        this.totalToPay = totalToPay;
    }
}